<script setup lang="ts">
defineOptions({
  name: "UserInfo"
});
import { reactive, ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import {
  selectServer,
  getServerPlan,
  editServerPlan,
  addServerPlan,
  deleteServerPlan,
  getContainer,
  getFloatingIpList,
  addFloatingIp,
  delFloatingIp,
  addFloatingIpBatch
} from "@/api/server";
import { message } from "@/utils/message";
import serverChart from "./components/serverChart.vue";
import VmList from "./components/VmList.vue";
const route = useRoute();
let serverMessage = ref({});
onMounted(async () => {
  TypeData.value = route.query.type;
  getFloating();
  let res = await selectServer({ server_id: route.query.server_id });
  serverMessage.value = res.data.data;
  await GetPlans();
  //获取所有容器
  let usertype = localStorage.getItem("user_type");
  if (usertype == "1") {
    containerBox.server_id = route.query.server_id;
    let cons = await getContainer(containerBox);
    user_servers.value = cons.data.data;
    total.value = cons.data.count;
  }
});
const TypeData = ref("");
//获取服务器套餐
const GetPlans = async () => {
  let plans = await getServerPlan({
    server_id: route.query.server_id,
    count: 30
  });
  console.log("服务器套餐", plans.data.data);
  plan_list.value = plans.data.data;
};
//获取浮动ip列表
const getFloating = async () => {
  let res = await getFloatingIpList({ server_id: route.query.server_id });
  floatList.value = res.data.data;
  floatTotal.value = res.data.count;
};
const floatTotal = ref(10);
const floatList = ref([]);
const floatVisible = ref(false);
const newFloatingIp = ref("");
//新增浮动ip
const ToAddFloatingIp = async () => {
  let arr = newFloatingIp.value.split("\n");
  let promises = arr.map(item => {
    return addFloatingIp({
      server_id: route.query.server_id,
      floating_ip: item
    }).then(res => {
      if (res.data.code !== 200) {
        return Promise.reject(new Error(`${res.data.message}`));
      }
      return res;
    });
  });
  try {
    const results = await Promise.allSettled(promises);
    let successCount = 0;
    let failList = [];
    results.forEach((result, index) => {
      if (result.status === "fulfilled") {
        successCount++;
      } else {
        failList.push(`IP ${arr[index]}: ${result.reason.message}`);
        message(`以下IP添加失败:IP ${arr[index]}: ${result.reason.message}`, {
          type: "error"
        });
      }
    });
    if (successCount > 0) {
      message(`${successCount}个IP添加成功`, { type: "success" });
    }
    getFloating();
    floatVisible.value = false;
  } catch (error) {
    message("处理过程中发生未知错误", { type: "error" });
  }
};

//删除浮动ip
const delFloating = async data => {
  let res = await delFloatingIp({ id: data });
  if (res.data.code == 200) {
    message("删除成功", { type: "success" });
    getFloating();
  }
};
//批量添加浮动IP
const addMore = ref(false);
const addr_floating_ip = ref("");
const start_ip = ref("");
const end_ip = ref("");
const ToAddMore = () => {
  addFloatingIpBatch({
    server_id: route.query.server_id,
    start_floating_ip: addr_floating_ip.value + "." + start_ip.value,
    end_floating_ip: addr_floating_ip.value + "." + end_ip.value
  }).then(res => {
    console.log("添加结果", res);
    if (res.data.code == 200) {
      message("添加成功", { type: "success" });
      addMore.value = false;
      getFloating();
    }
  });
};
//容器相关数据
const containerBox = reactive({
  server_id: "",
  page: 1,
  count: 10,
  key: "",
  user_id: ""
});
//修改新增套餐的弹窗开关变量
const centerDialogVisible = ref(false);
//修改或新增套餐的判断
const addOrChange = ref(false);
const editPlan = async () => {
  centerDialogVisible.value = false;
  if (addOrChange.value) {
    let res = await addServerPlan({
      ...plan_form,
      server_id: route.query.server_id
    });
    if (res.data.code == 200) {
      message("添加成功！", { type: "success" });
    }
  } else {
    let res = await editServerPlan(plan_form);
    if (res.data.code == 200) {
      message("修改成功！", { type: "success" });
    }
  }
  //更新服务器套餐
  await GetPlans();
};
//删除套餐
const deletePlan = async data => {
  let res = await deleteServerPlan({
    plan_id: data,
    server_type: TypeData.value
  });
  if (res.data.code == 200) {
    message("删除成功！", { type: "success" });
    //更新服务器套餐
    await GetPlans();
  }
};

const plan_list = ref([]);
//容器列表
const user_servers = ref([]);
//容器分页
const total = ref(10);
const handleCurrentPageChange = async newPage => {
  containerBox.page = newPage;
  let cons = await getContainer(containerBox);
  user_servers.value = cons.data.data;
};
const handlePageSizeChange = async newSize => {
  containerBox.count = newSize;
  let cons = await getContainer(containerBox);
  user_servers.value = cons.data.data;
};

const plan_form = reactive({
  plan_id: "1",
  name: "基础套餐",
  memory: "100",
  disk: "200",
  cpu: "200",
  price: "18",
  bandwidth_rx: "100",
  bandwidth_tx: "100",
  threshold_rx: "100",
  threshold_tx: "20",
  port_num: "",
  snapshot_num: "",
  number: "38",
  volume_price: "",
  min_iops: "",
  max_iops: "",
  description: "基础套餐，一般用于建站使用",
  must_real_name: 0
});
function show_table(data = null) {
  if (!data) {
    // 当data未传值，视为新增套餐
    // 遍历form对象的每个键值对
    Object.keys(plan_form).forEach(key => {
      plan_form[key] = null;
    });
  } else {
    // data传值，视为修改套餐
    // 遍历data对象的每个键值对
    Object.keys(data).forEach(key => {
      plan_form[key] = data[key];
    });
  }
}
//复制内容
const copytext = ref({});
const copyit = async () => {
  copytext.value = JSON.parse(JSON.stringify(plan_form));
  message("复制成功", { type: "success" });
  await navigator.clipboard.writeText(JSON.stringify(copytext.value));
};
const getit = async () => {
  try {
    let text = await navigator.clipboard.readText();
    let objet = JSON.parse(text);
    Reflect.deleteProperty(objet, "plan_id");
    Object.keys(objet).forEach(key => {
      plan_form[key] = objet[key];
    });
    message("粘贴成功", { type: "success" });
    console.log(objet);
    return objet;
  } catch (err) {
    message("无法读取剪贴板内容,请检查获取到的格式", { type: "error" });
  }
};
</script>

<template>
  <div class="body">
    <el-descriptions title="服务器信息" direction="vertical" :column="4" size="default" border>
      <el-descriptions-item label="服务器 ID">{{
        serverMessage.server_id
        }}</el-descriptions-item>
      <el-descriptions-item label="服务器名称">{{
        serverMessage.name
        }}</el-descriptions-item>
      <el-descriptions-item label="IP地址" :span="2">{{
        serverMessage.server_ip
        }}</el-descriptions-item>
      <el-descriptions-item label="创建时间">
        <el-tag size="small">{{ serverMessage.created_at }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="地点">
        {{ serverMessage.location }}
      </el-descriptions-item>
      <el-descriptions-item label="带宽">{{ serverMessage.bandwidth }}mbps
      </el-descriptions-item>
      <el-descriptions-item label="硬盘">{{ serverMessage.disk }}GB
      </el-descriptions-item>
      <el-descriptions-item label="CPU">{{ serverMessage.cpu }}核心
      </el-descriptions-item>
      <el-descriptions-item label="状态"><el-tag :type="serverMessage.state == 0 ? 'error' : 'success'">{{
        serverMessage.state == 0 ? "离线" : "在线"
          }}</el-tag></el-descriptions-item>
    </el-descriptions>

    <serverChart v-if="TypeData" :Type="TypeData" />

    <!-- tab栏 -->
    <el-tabs type="border-card" class="info_table">
      <el-tab-pane label="套餐列表">
        <div class="btn_list">
          <el-button type="primary" @click="
            show_table();
          centerDialogVisible = true;
          addOrChange = true;
          ">添加套餐
          </el-button>
        </div>
        <div class="plan_card_list">
          <el-card v-for="plan in plan_list" style="max-width: 480px" body-style="padding:5px;" shadow="hover"
            class="plan_card">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="套餐ID" label-align="right" align="center">{{ plan.plan_id
                }}</el-descriptions-item>
              <el-descriptions-item label="套餐名称" label-align="right" align="center">{{ plan.name
                }}</el-descriptions-item>
              <el-descriptions-item label="内存" label-align="right" align="center">{{ plan.memory }}
                MB</el-descriptions-item>
              <el-descriptions-item label="硬盘" label-align="right" align="center">
                {{ plan.disk }} GB
              </el-descriptions-item>
              <el-descriptions-item label="CPU" label-align="right" align="center">{{ plan.cpu }}
                vCpu</el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'dockerContainer'" label="上行带宽" label-align="right"
                align="center">{{ plan.bandwidth_tx }} mbps</el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'dockerContainer'" label="下行带宽" label-align="right"
                align="center">{{ plan.bandwidth_rx }} mbps</el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'dockerContainer'" label="上行流量阈值" label-align="right"
                align="center">{{ plan.threshold_tx }} mbps</el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'dockerContainer'" label="下行流量阈值" label-align="right"
                align="center">{{ plan.threshold_rx }} mbps</el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'hyperV'" label="默认允许开放端口数" label-align="right" align="center">{{
                plan.port_num }}
              </el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'hyperV'" label="默认允许快照数" label-align="right" align="center">{{
                plan.snapshot_num }}
              </el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'hyperV'" label="读写限制(1iops=8kb/s)" label-align="right"
                align="center">{{ plan.min_iops }}/iops
              </el-descriptions-item>
              <el-descriptions-item v-if="TypeData == 'hyperV'" label="读写最大突发(1iops=8kb/s)" label-align="right"
                align="center">{{ plan.max_iops }}/iops
              </el-descriptions-item>

              <el-descriptions-item label="剩余数量" label-align="right" align="center">{{ plan.number
                }}</el-descriptions-item>
              <el-descriptions-item label="价格" label-align="right" align="center">{{ plan.price }}
                元</el-descriptions-item>
              <el-descriptions-item label="额外硬盘价格" label-align="right" align="center">{{ plan.volume_price }}
                元</el-descriptions-item>
              <el-descriptions-item label="描述" label-align="right" align="center" span="2">{{ plan.description
                }}</el-descriptions-item>
              <el-descriptions-item label="操作" label-align="right" align="center">
                <el-button size="small" type="success" text bg @click="
                  show_table(plan);
                centerDialogVisible = true;
                addOrChange = false;
                ">编辑</el-button>
                <el-button size="small" type="danger" text bg @click="deletePlan(plan.plan_id)">删除</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="TypeData == 'dockerContainer'" label="容器列表">
        <el-table class="table_el" :data="user_servers" style="width: auto">
          <el-table-column label="ID" prop="container_id" />
          <el-table-column label="购买价格" prop="pay" />
          <el-table-column label="购买时间">
            <template #default="scope">
              {{ scope.row.created_at }}
            </template>
          </el-table-column>
          <el-table-column label="到期时间">
            <template #default="scope">
              {{ scope.row.become_time }}
            </template>
          </el-table-column>
          <el-table-column label="所属套餐" prop="plan_id" />
          <el-table-column label="用户ID" prop="user_id" />
          <el-table-column label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.container_state == 0 ||
                  scope.row.container_state == 1
                  ? 'info'
                  : scope.row.container_state == 2
                    ? 'success'
                    : 'danger'
                ">{{
                  scope.row.container_state == 0
                    ? "未支付"
                    : scope.row.container_state == 1
                      ? "未开通"
                      : scope.row.container_state == 2
                        ? "开机"
                        : "关机"
                }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="230">
            <template #header>
              <el-input v-model="containerBox.key" size="small" placeholder="关键字筛选" />
            </template>
            <template #default="scope">
              <el-button size="small"><router-link :to="'/servers/containers?container_id=' + scope.row.container_id
                ">管理</router-link></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination background layout="prev, pager, next,sizes" :total="total" :current-page="containerBox.page"
          :page-size="containerBox.count" :page-sizes="[1, 5, 10]" @update:current-page="handleCurrentPageChange"
          @update:page-size="handlePageSizeChange" />
      </el-tab-pane>
      <el-tab-pane v-if="TypeData == 'hyperV'" label="虚拟机列表" :lazy="true">
        <VmList :ID="serverMessage.server_id" />
      </el-tab-pane>
      <el-tab-pane v-if="TypeData == 'dockerContainer'" label="浮动IP池" :lazy="true">
        <el-button type="primary" plain @click="floatVisible = true">添加浮动IP</el-button>
        <el-button type="primary" plain @click="addMore = true">批量添加浮动IP</el-button>
        <el-table class="table_el" :data="floatList" style="width: auto">
          <el-table-column label="ID" prop="id" />
          <el-table-column label="创建时间">
            <template #default="scope">
              {{ scope.row.created_at }}
            </template>
          </el-table-column>
          <el-table-column label="浮动IP" prop="floating_ip" />
          <el-table-column label="占用情况">
            <template #default="scope">
              <el-tag :type="scope.row.is_used ? 'success' : 'info'">{{
                scope.row.is_used ? "已绑定" : "未绑定"
                }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="230">
            <template #header> 操作 </template>
            <template #default="scope">
              <el-button type="danger" size="small" @click="delFloating(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 套餐修改 -->
    <el-dialog v-model="centerDialogVisible" :title="addOrChange ? '添加套餐' : '编辑套餐'" width="500" center>
      <div>
        <el-form label-width="auto" :model="plan_form" style="max-width: 600px">
          <el-form-item label="套餐名称">
            <el-input v-model="plan_form.name" style="width: 240px" placeholder="请输入套餐名称" />
          </el-form-item>
          <el-form-item label="内存">
            <el-input v-model="plan_form.memory" placeholder="内存限制/MB (1GB=1000MB)" style="width: 240px"
              type="number" />
          </el-form-item>
          <el-form-item label="硬盘">
            <el-input v-model="plan_form.disk" placeholder="硬盘限制/GB" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item :label="TypeData == 'dockerContainer' ? 'CPU(毫核)' : 'CPU(核)'">
            <el-input v-model="plan_form.cpu" :placeholder="TypeData == 'dockerContainer'
                ? 'CPU 限制/毫核 (1核=1000毫核)'
                : 'CPU 限制/核'
              " style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'dockerContainer'" label="上行带宽">
            <el-input v-model="plan_form.bandwidth_tx" placeholder="上行带宽/mbps" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'dockerContainer'" label="下行带宽">
            <el-input v-model="plan_form.bandwidth_rx" placeholder="下行带宽/mbps" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'dockerContainer'" label="量阈值/上行">
            <el-input v-model="plan_form.threshold_tx" placeholder="上行流量报警阈值 /mbps" style="width: 240px"
              type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'dockerContainer'" label="量阈值/下行">
            <el-input v-model="plan_form.threshold_rx" placeholder="下行流量报警阈值 /mbps" style="width: 240px"
              type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'hyperV'" label="默认允许开放端口数">
            <el-input v-model="plan_form.port_num" placeholder="默认允许开放端口数" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'hyperV'" label="默认允许快照数">
            <el-input v-model="plan_form.snapshot_num" placeholder="默认允许快照数" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'hyperV'" label="读写限制(1iops=8kb/s)">
            <el-input v-model="plan_form.min_iops" placeholder="读写限制(1iops=8kb/s)默认2000" style="width: 240px"
              type="number" />
          </el-form-item>
          <el-form-item v-if="TypeData == 'hyperV'" label="读写最大突发(1iops=8kb/s)">
            <el-input v-model="plan_form.max_iops" placeholder="读写最大突发(1iops=8kb/s)默认2000" style="width: 240px"
              type="number" />
          </el-form-item>
          <el-form-item label="套餐库存数量">
            <el-input v-model="plan_form.number" placeholder="库存数量/个" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item label="价格">
            <el-input v-model="plan_form.price" placeholder="价格/元" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item label="额外硬盘价格">
            <el-input v-model="plan_form.volume_price" placeholder="额外硬盘价格/元" style="width: 240px" type="number" />
          </el-form-item>
          <el-form-item label="是否需要实名">
            <el-select v-model="plan_form.must_real_name" placeholder="请选择" style="width: 240px">
              <el-option label="需要实名" :value="1" />
              <el-option label="不需要实名" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="plan_form.description" placeholder="对套餐的介绍" style="width: 240px" type="textarea"
              :rows="2" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="getit">一键粘贴内容</el-button>
          <el-button @click="copyit">一键复制内容</el-button>
          <el-button @click="centerDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="editPlan"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="floatVisible" title="浮动IP">
      <div>
        <el-form label-width="auto" style="max-width: 600px">
          <el-form-item label="浮动ip地址">
            <el-input v-model="newFloatingIp" style="width: 240px" :autosize="{ minRows: 3, maxRows: 10 }"
              type="textarea" placeholder="每个ip一行，换行下一个" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="floatVisible = false">关闭</el-button>
          <el-button type="primary" @click="ToAddFloatingIp"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="addMore" title="浮动IP">
      <div>
        <el-form label-width="auto" style="max-width: 600px">
          <el-form-item label="起始浮动ip地址">
            <el-input v-model="addr_floating_ip" placeholder="如：11.11.11" style="width: 140px" />.
            <el-input v-model="start_ip" placeholder="11" style="width: 40px" />
          </el-form-item>
          <el-form-item label="结束浮动ip地址">
            <el-input v-model="addr_floating_ip" placeholder="如：11.11.11" style="width: 140px" />.
            <el-input v-model="end_ip" placeholder="14" style="width: 40px" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addMore = false">关闭</el-button>
          <el-button type="primary" @click="ToAddMore"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-descriptions {
  margin-top: 20px;
}

.info_table {
  margin: 20px 0;
}

.plan_card_list {
  display: flex;
  flex-wrap: wrap;
}

.plan_card {
  margin: 10px;
}

.btn_list {
  margin: 5px;
}
</style>
